<template>
  <div class="settings">
    <el-card>
      <template #header>
        <div class="settings-header">
          <h2>系统设置</h2>
        </div>
      </template>

      <el-form :model="form" label-width="120px" @submit.prevent="saveSettings">
        <el-form-item 
          label="API 密钥"
          :error="apiKeyError"
        >
          <el-input
            v-model="form.apiKey"
            type="password"
            placeholder="请输入 DeepSeek API 密钥"
            show-password
            @input="clearApiKeyError"
          />
          <div class="form-item-tip">
            <el-link 
              type="primary" 
              href="https://platform.deepseek.com/" 
              target="_blank"
            >
              获取 API 密钥
            </el-link>
          </div>
        </el-form-item>

        <el-form-item label="默认温度">
          <el-slider
            v-model="form.temperature"
            :min="0"
            :max="1"
            :step="0.1"
            show-input
          />
          <div class="form-item-tip">
            较高的值会使输出更加随机，较低的值会使输出更加集中和确定
          </div>
        </el-form-item>

        <el-form-item label="最大长度">
          <el-input-number
            v-model="form.maxTokens"
            :min="100"
            :max="2000"
            :step="100"
          />
          <div class="form-item-tip">
            控制生成文本的最大长度，较大的值可能会增加响应时间
          </div>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="saveSettings" :loading="loading">
            保存设置
          </el-button>
          <el-button @click="resetSettings" :disabled="loading">
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import type { UserSettings } from '@/api/types'
import { deepseekApi } from '@/api/deepseek'

const DEFAULT_SETTINGS: UserSettings = {
  apiKey: '',
  temperature: 0.7,
  maxTokens: 1000
}

const form = ref<UserSettings>({ ...DEFAULT_SETTINGS })
const loading = ref(false)
const apiKeyError = ref('')

const clearApiKeyError = () => {
  apiKeyError.value = ''
}

const loadSettings = () => {
  form.value = {
    apiKey: localStorage.getItem('deepseek_api_key') || '',
    temperature: Number(localStorage.getItem('default_temperature')) || DEFAULT_SETTINGS.temperature,
    maxTokens: Number(localStorage.getItem('default_max_tokens')) || DEFAULT_SETTINGS.maxTokens
  }
}

const validateApiKey = async (apiKey: string): Promise<boolean> => {
  try {
    const response = await deepseekApi.validateApiKey(apiKey)
    return response.data
  } catch (error) {
    return false
  }
}

const saveSettings = async () => {
  try {
    loading.value = true
    clearApiKeyError()

    // 如果API密钥已更改，则验证新密钥
    const oldApiKey = localStorage.getItem('deepseek_api_key')
    if (form.value.apiKey && form.value.apiKey !== oldApiKey) {
      const isValid = await validateApiKey(form.value.apiKey)
      if (!isValid) {
        apiKeyError.value = 'API 密钥无效'
        return
      }
    }
    
    // 保存到本地存储
    localStorage.setItem('deepseek_api_key', form.value.apiKey)
    localStorage.setItem('default_temperature', form.value.temperature.toString())
    localStorage.setItem('default_max_tokens', form.value.maxTokens.toString())
    
    ElMessage.success('设置保存成功')
  } catch (error) {
    if (error instanceof Error) {
      ElMessage.error(`保存设置失败: ${error.message}`)
    } else {
      ElMessage.error('保存设置失败，请重试')
    }
    console.error('保存设置失败:', error)
  } finally {
    loading.value = false
  }
}

const resetSettings = () => {
  form.value = { ...DEFAULT_SETTINGS }
  ElMessage.info('设置已重置，请记得保存')
}

onMounted(() => {
  loadSettings()
})
</script>

<style scoped lang="scss">
.settings {
  max-width: 600px;
  margin: 0 auto;
  padding: 20px;

  .settings-header {
    text-align: center;
    h2 {
      margin: 0;
    }
  }

  .form-item-tip {
    font-size: 12px;
    color: #909399;
    margin-top: 4px;
  }

  :deep(.el-slider) {
    width: 100%;
  }

  :deep(.el-input-number) {
    width: 180px;
  }
}
</style> 